package LC;

import java.util.Stack;

/**
 * https://leetcode.com/problems/simplify-path/description/
 * Given an absolute path for a file (Unix-style), simplify it.
 * For example,
 * path = "/home/", => "/home"
 * path = "/a/./b/../../c/", => "/c"
 */
public class LC_071_SimplifyPath_Stack_String_Switch {
    public static void main(String[] args) {
        System.out.println(Solution.simplifyPath("/home/"));
        System.out.println(Solution.simplifyPath("/a/./b/../../c/"));
    }

    static class Solution {
        static String simplifyPath(String path) {
            String[] pathArray = path.split("/");
            Stack<String> stack = new Stack<>();
            StringBuilder result = new StringBuilder();
            for (String aPathArray : pathArray) {
                switch (aPathArray) {
                    case "":
                    case ".":
                        break;
                    case "..":
                        if (!stack.isEmpty())
                            stack.pop();
                        break;
                    default:
                        stack.push(aPathArray);
                        break;
                }
            }
            if (stack.isEmpty())
                return "/";
            while (!stack.isEmpty())
                result.insert(0, "/" + stack.pop());
            return result.toString();
        }
    }
}
